package com.tencent.timsdk.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.tencent.timsdk.interf.ChatView;
import com.tencent.timsdk.interf.EndlessRecyclerOnScrollListener;

/**
 * 聊天界面输入控件
 */
public class ChatRecyclerView extends RecyclerView {

    private ChatView chatView;

    public ChatRecyclerView(Context context) {
        super(context);
        init();
    }

    public ChatRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ChatRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    /**
     * 关联聊天界面逻辑
     */
    public void setChatView(ChatView chatView) {
        this.chatView = chatView;
    }


    private void init() {
        addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (chatView != null){
                        chatView.onRecyclerViewTouch();
                    }
                }
                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView rv, MotionEvent e) {
            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
            }
        });
        addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (bottom < oldBottom) {
                    if (chatView != null){
                        chatView.onSoftKeyboardShow();
                    }
                    LinearLayoutManager manager = (LinearLayoutManager) getLayoutManager();
                    int firstItemPosition = manager.findFirstCompletelyVisibleItemPosition();
                    if (!manager.getStackFromEnd() && firstItemPosition > 0) {
                        manager.setStackFromEnd(true);
                    }
                }
            }
        });
        addOnScrollListener(new EndlessRecyclerOnScrollListener() {

            @Override
            public void onTopLoadMore(int lastItemPosition) {
                //如果拉到顶端读取更多消息
                if (chatView != null){
                    chatView.onTopLoadMore(lastItemPosition);
                }
            }
        });
    }
}
